const Koa = require('koa')
const Router = require('koa-router')
const { koaBody } = require('koa-body')
const path = require('path')

const static = require('koa-static')

const { renderIndex, checkClassDir, checkUserFile, saveFile, getProjectList, checkClassDirExists, getClassList } = require("./router")
const { parseArgs } = require("./utils")

// 解析命令行参数
const args = parseArgs(process.argv)

// 判断是否传入 port 参数
if (args.port) {
    process.env.PORT = args.port
}

const port = process.env.PORT || 5173




// 实例化 Koa 对象和 Router 对象
const app = new Koa()
const router = new Router()

// 静态资源服务
app.use(static(path.join(__dirname, 'dist')))

// 渲染 index.html
router.get('/', renderIndex)

// 上传文件接口
router.post('/api/upload', koaBody({ multipart: true }), checkClassDir, checkUserFile, saveFile)


// 获取 uploads 目录下的文件列表
router.get('/api/list/:classId', checkClassDirExists, getProjectList)

// 获取 班级 列表
router.get('/api/classes', getClassList)

app
    .use(router.routes())
    .use(router.allowedMethods())

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`)
})
